/**
 * 地址相关
 */
import {
    takeEvery,
    delay,
    takeLatest,
    buffers,
    channel,
    eventChannel,
    END
} from 'redux-saga'
import {
    race,
    put,
    call,
    take,
    fork,
    select,
    actionChannel,
    cancel,
    cancelled
} from 'redux-saga/effects'

import {
    GET_ADDRESS_LIST_ASYNC,
    ADD_ADDRESS_LIST,
    GET_DEFAULT_ADDRESS_ASYNC,
    ADD_DEFAULT_ADDRESS,
} from '../actions/actionsTypes'

//service
import addressServices from '../services/addressService'

import { Toast } from 'antd-mobile' //UI
import ChMessage from '../utils/message.config'

import { normalize, schema } from 'normalizr'; //范式化库

// 获取默认地址
function* getDefaultAddress(action) {
    Toast.loading('', 0)
    try {
        let { result, timeout } = yield race({
            result: call(addressServices.getDefault, action.data),
            timeout: call(delay, 30000)
        })
        Toast.hide();
        if (timeout) {
            Toast.info(ChMessage.FETCH_OVERTIME);
        } else {
            if (result.code == "1000") {
                yield put({ type: ADD_DEFAULT_ADDRESS, data: result.body })
                if (action.callback) {
                    action.callback(result)
                }
            }else{
                Toast.info(result.msg);
            }
        }
    } catch (error) {
        Toast.hide();
        Toast.info(ChMessage.FETCH_FAILED);
    }
}

function* watchGetDefaultAddress() {
    yield takeLatest(GET_DEFAULT_ADDRESS_ASYNC, getDefaultAddress)
}

// 获取地址列表
function* getAddressList(action) {
    Toast.loading('', 0)
    try {
        let { result, timeout } = yield race({
            result: call(addressServices.getList, action.data),
            timeout: call(delay, 30000)
        })
        Toast.hide();
        if (timeout) {
            Toast.info(ChMessage.FETCH_OVERTIME);
        } else {
            if (result.code == "1000") {
                yield put({ type: ADD_ADDRESS_LIST, data: result.body.addressMsgList })
                if (action.callback) {
                    action.callback(result)
                }
            }else{
                Toast.info(result.msg);
            }
        }
    } catch (error) {
        Toast.hide();
        Toast.info(ChMessage.FETCH_FAILED);
    }
}

function* watchGetAddressList() {
    yield takeLatest(GET_ADDRESS_LIST_ASYNC, getAddressList)
}

export function* watchAddressFetch() {
    yield [
        fork(watchGetAddressList),
        fork(watchGetDefaultAddress),
    ]
}